<?php
function renren_api_handle() {
  try {
    require_once('renren.config.inc');//$config
    require_once('renren.common.inc');
    $renren_oauth = new RenRenOauth($config);//$config defined in "reren.config.inc"

    if (isset ($_SESSION['renren_session']['session_key'])) {
      //alreadly authorize.
      header('Location: ' . SITE_URL);
      exit();
    } else {
      //Need authorize
      if (!$_GET['code'] && !$_SESSION['session_code']) {
        //Do authorization.
        $auth_url = $renren_oauth->getAuthorizeUrl();
        header("Location: {$auth_url}");
      }
      else if ($_GET['code']) {
        $code = $_GET['code'];
        //Get access token
        $token = $renren_oauth->getAccessToken($code);//array('expires_in' => '', 'user' => '', 'refresh_token' => '', 'access_token' => '') ;
        echo '<h1>access token</h1>';print_pre($token);
        $session_key = $renren_oauth->getSessionKey($token['access_token']);
        echo '<h1>session key</h1>';print_pre($session_key);
        $data = array(
          'code' => $code,
          'access_token' => $token['access_token'],
          'refresh_token' => $token['refresh_token'],
          'expires_in' => $token['expires_in'],
          'uid' => $session_key['user']['id'],
          'session_secret' => $session_key['renren_token']['session_secret'],
          'session_key' => $session_key['renren_token']['session_key'],
          'user' => serialize($token['user'])
        );
        $_SESSION['renren_session'] = $data;

        //RenRen user sign in.
        //TODO login user.
        $renren_user = array(
          'renren_uid' => $token['user']['id'],
          'renren_name' => $token['user']['name']
        );
        renren_user_login_register($renren_user, 'renren');
        header('Location: ' . SITE_URL);
        exit();
      }
    }
  } catch(Exception $e) {
    echo $e->getMessage();
  }
}

function renren_user_login_register($renren_user, $module) {
  global $user;

  $name = 'RenRen_' . $renren_user['renren_uid'];
  $existing_user = user_load(array('name' => $name));
  if (isset($existing_user->uid)) {
    $user = $existing_user;
  }
  else {
    // Register this new user.
    $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      "authname_$module" => $name,
      'access' => time(),
      'profile_nickname' => $renren_user['renren_name']
    );
    $account = user_save('', $userinfo);
    // Terminate if an error occured during user_save().
    if (!$account) {
      drupal_set_message(t("Error saving user account."), 'error');
      return;
    }
    $user = $account;
    watchdog('user', 'New external user: %name using module %module.', array('%name' => $name, '%module' => $module), WATCHDOG_NOTICE, l(t('edit'), 'user/'. $user->uid .'/edit'));
  }

}


function renren_show($config) {
    $oauth = new RenRenOauth($config);//$config defined in "reren.config.inc"
    $client = new RenRenClient($config);// api调用时实例化RenRenClient对象，oauth授权时实例化RenRenOauth对象

    // 如果您应该通过其他sdk（或自己实现）获得了session key，那么您可以选择只使用该sdk中的api部分
    // 您可以通过setSessionKey方法设置您已经获取到的session key。
    $session_key = $_SESSION['session_renren']['renren_token']['session_key'];//TODO
    $client->setSessionKey($session_key);
    /*$friends = $client->POST('friends.getFriends', array('1', '100'));//
    print_pre($friends);*/

    //$userinfo = $client->POST('users.getProfileInfo', array($_SESSION['session_renren']['user']['id'], ''));
    //print_pre($userinfo);

    $data = array(
      'oauth' =>$oauth,
      'client' => $client,
      'auth_url' =>  $oauth->getAuthorizeUrl(),
    );
    $latest_votes = array(2);
    $most_votes = array(3);
    return theme('vote_welcome' , $data, $latest_votes, $most_votes);
}

function renren_insert_token() {//TODO
  $sql = "INSERT INTO renren_token (session_key, session_secret, refresh_token, access_token, renren_uid, code, expires_in) " .
              " VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')";
  $query = db_query($sql);
}
